package com.example.homework.fragment;

import android.app.AlarmManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.homework.R;
import com.example.homework.activity.TodoEditActivity;
import com.example.homework.adapter.TodoAdapter;
import com.example.homework.bean.TodoItem;
import com.example.homework.bean.TodoReminderReceiver;

import java.util.ArrayList;
import java.util.List;

public class NearbyFragment extends Fragment implements TodoAdapter.OnItemClickListener {
    private RecyclerView recyclerView;
    private TodoAdapter adapter;
    private List<TodoItem> todoList = new ArrayList<>();
    private int nextId = 1; // 自增 ID 生成器
    private static final int REQUEST_ADD_TODO = 100;
    private static final int REQUEST_EDIT_TODO = 200;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_nearby, container, false);

        // 初始化 RecyclerView
        recyclerView = view.findViewById(R.id.recyclerViewTodo);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        adapter = new TodoAdapter(todoList, this); // 传递当前 Fragment 作为事件监听器
        recyclerView.setAdapter(adapter);

        // 初始化添加按钮
        Button btnAddTodo = view.findViewById(R.id.btnAddTodo);
        btnAddTodo.setOnClickListener(v -> openAddTodoActivity());

        return view;
    }

    // 添加待办事项（打开编辑页面）
    private void openAddTodoActivity() {
        Intent intent = new Intent(requireContext(), TodoEditActivity.class);
        startActivityForResult(intent, REQUEST_ADD_TODO);
    }

    // 编辑待办事项
    private void openEditTodoActivity(TodoItem item) {
        Intent intent = new Intent(requireContext(), TodoEditActivity.class);
        intent.putExtra("id", item.getId());
        intent.putExtra("title", item.getTitle());
        intent.putExtra("description", item.getDescription());
        intent.putExtra("reminderTime", item.getReminderTime());
        startActivityForResult(intent, REQUEST_EDIT_TODO);
    }

    // 处理 Activity 返回结果（添加/编辑待办）
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            int id = data.getIntExtra("id", -1);
            String title = data.getStringExtra("title");
            String description = data.getStringExtra("description");
            long reminderTime = data.getLongExtra("reminderTime", 0);

            if (requestCode == REQUEST_ADD_TODO) {
                // 新增待办
                TodoItem newItem = new TodoItem(nextId++, title, description, reminderTime, false);
                todoList.add(newItem);
                setReminder(newItem); // 设置提醒
            } else if (requestCode == REQUEST_EDIT_TODO) {
                // 编辑待办
                TodoItem editedItem = findTodoById(id);
                if (editedItem != null) {
                    editedItem.setTitle(title);
                    editedItem.setDescription(description);
                    editedItem.setReminderTime(reminderTime);
                    setReminder(editedItem); // 更新提醒时间
                }
            }
            adapter.notifyDataSetChanged(); // 刷新列表
        }
    }

    // 根据 ID 查找待办事项
    private TodoItem findTodoById(int id) {
        for (TodoItem item : todoList) {
            if (item.getId() == id) {
                return item;
            }
        }
        return null;
    }

    // 设置提醒时间（AlarmManager）
    private void setReminder(TodoItem item) {
        AlarmManager alarmManager = (AlarmManager) requireContext().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(requireContext(), TodoReminderReceiver.class);
        intent.putExtra("todoId", item.getId());

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                requireContext(),
                item.getId(),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        alarmManager.setExact(AlarmManager.RTC_WAKEUP, item.getReminderTime(), pendingIntent);
    }

    // -------------------- TodoAdapter.OnItemClickListener 回调实现 --------------------
    @Override
    public void onEditClick(TodoItem item) {
        openEditTodoActivity(item);
    }

    @Override
    public void onDeleteClick(TodoItem item) {
        todoList.remove(item);
        adapter.notifyDataSetChanged();
        // 取消已设置的提醒（可选）
        cancelReminder(item);
    }

    @Override
    public void onItemClick(TodoItem item) {
        item.setCompleted(!item.isCompleted());
        adapter.notifyItemChanged(todoList.indexOf(item));
        // 可在此处添加完成状态持久化逻辑（如数据库更新）
    }

    // 取消提醒（删除待办时调用）
    private void cancelReminder(TodoItem item) {
        AlarmManager alarmManager = (AlarmManager) requireContext().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(requireContext(), TodoReminderReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                requireContext(),
                item.getId(),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        alarmManager.cancel(pendingIntent);
    }
}